package com.zjkj.mp.controller.listener;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;


public class LoginSessionListener implements HttpSessionAttributeListener{

	//Log log = LogFactory.getLog(this.getClass());
	Map<String, HttpSession> map = new HashMap<String, HttpSession>();
	@Override
	public void attributeAdded(HttpSessionBindingEvent event) {
		// TODO Auto-generated method stub
		String name = event.getName();
		if(name.equalsIgnoreCase("usernameid")){
			String usernameid = (String) event.getValue();
			if(map.get(usernameid) != null){
				HttpSession session = map.get(usernameid);	
				session.removeAttribute("usernameid");
				session.removeAttribute("username");
				session.removeAttribute("usernamelx");
				session.removeAttribute("userqx");
				session.setAttribute("msg", "您的账号已经在别处登录，请退出后再登录！");
			}
			map.put(usernameid, event.getSession());
		}
	}

	@Override
	public void attributeRemoved(HttpSessionBindingEvent event) {
		// TODO Auto-generated method stub
		String name = event.getName();
		if(name.equals("usernameid")){
			String usernameid = (String) event.getValue();
			map.remove(usernameid);
		}
	}

	@Override
	public void attributeReplaced(HttpSessionBindingEvent event) {
		// TODO Auto-generated method stub
		String name = event.getName();
		if(name.equals("usernameid")){
			String oldusernameid = (String) event.getValue();
			map.remove(oldusernameid);
			
			String usernameid = (String) event.getSession().getAttribute("usernameid");
			
			if(map.get(usernameid) != null){
				HttpSession session = map.get(usernameid);
				session.removeAttribute("usernameid");
				session.removeAttribute("username");
				session.removeAttribute("usernamelx");
				session.removeAttribute("userqx");
				session.setAttribute("msg", "您的账号已经在别处登录，请退出后再登录！");
			}
			map.put(usernameid, event.getSession());
		}
	}

}
